class OauthController < ApplicationController 
  def index
    redirect_to :action=>"index" unless SERVICE_CONFIG.respond_to? "[]"
  end
  
  def set_service_info
    # consumer 설정을 하기 위해 DB를 사용하는 것이 오버인듯 하여 FileSystem을 사용함
    SERVICE_CONFIG["consumer_key"] = params[:consumer_key] if params[:consumer_key] 
    SERVICE_CONFIG["consumer_secret"] = params[:consumer_secret] if params[:consumer_secret] 
    SERVICE_CONFIG["site"] = params[:site] if params[:site] 
    File.open("#{RAILS_ROOT}/config/service_info.oauth.yml", "w+").write SERVICE_CONFIG.to_yaml.to_s
    sleep(2)
    redirect_to :action=>"index"
  end
  
  def start_request 
    @request_token = MyToken.consumer.get_request_token
    @request_token = (MyToken.create(:key=>@request_token.token, :secret=>@request_token.secret)).as_request_token
    session[:request_token] = @request_token.token
    redirect_to @request_token.authorize_url
  end
  
  def callback
    @request_token = (MyToken.find_by_key(session[:request_token])).as_request_token
    @access_token = @request_token.get_access_token
    @access_token = (MyToken.create(:key=>@access_token.token,:secret=>@access_token.secret)).as_access_token
    session[:access_token] = @access_token.token
    redirect_to :action=>"show"
  end
  
  def whisper_test
    @access_token ||= (MyToken.find_by_key(session[:access_token])).as_access_token    
    params[:openid_to] ||= "http://humbroll.myid.net/"
    params[:message] ||= "whisper oauth test message"
    res = @access_token.post("/api/send", {:openid_to=>params[:openid_to], :message=>params[:message]}, {})
    flash[:message] = "Response : #{res.code}"
    redirect_to :action=>"show"
  end
  
  def show
    @access_token ||= MyToken.find_by_key(session[:access_token])
    flash[:access_token] = "access_token:#{@access_token.key}<br/>access_token_secret:#{@access_token.secret}"
  end
end

